package com.itheima.easy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.easy.base.PageResponse;
import com.itheima.easy.entity.Balance;
import com.itheima.easy.exception.BaseException;
import com.itheima.easy.mapper.BalanceMapper;
import com.itheima.easy.service.BalanceService;
import com.itheima.easy.vo.BalanceVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 余额服务
 */
@Service
public class BalanceServiceImpl implements BalanceService {

    @Resource // 注入BalanceMapper
    BalanceMapper balanceMapper;

    @Override // 重写selectByElderId方法
    public Balance selectByElderId(Long elderId) {
        return balanceMapper.selectByElderId(elderId); // 调用BalanceMapper的selectByElderId方法
    }

    @Override // 重写save方法
    public void save(Balance balance) {
        balanceMapper.updateByPrimaryKey(balance); // 调用BalanceMapper的updateByPrimaryKey方法
    }

    @Override // 重写page方法
    public PageResponse<BalanceVo> page(String bedNo, String elderName, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize); // 使用PageHelper进行分页
        Page<Balance> page =  balanceMapper.page(bedNo, elderName); // 调用BalanceMapper的page方法
        return PageResponse.of(page, BalanceVo.class); // 返回分页结果
    }

    /**
     * 关闭余额账户
     * @param elderId 老人id
     * @param deductions 扣除金额
     * @throws BaseException 关闭余额账户失败
     */
    @Override
    public void close(Long elderId, BigDecimal deductions) throws BaseException {
        Balance balance = balanceMapper.selectByElderId(elderId);
        if (deductions.compareTo(balance.getPrepaidBalance()) == 0) {
            balanceMapper.deleteByPrimaryKey(balance.getId());
            return;
        }
        throw new BaseException("关闭余额账户失败");
    }
}
